package com.eco.fanliapp.job.goodsjob;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.YoungmallItemInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.client.HttpClient;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * 获取羊毛省钱推荐商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class YoungmallTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(YoungmallTask.class);

    @Autowired
    private IAppGoodsService appGoodsService;

    @Autowired
    RedisTemplateService redisTemplateService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private FindItemIdUtils taoBaoUtils;

    public YoungmallTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行定时任务-获取羊毛省钱首页推荐商品-YoungmallTask：executeCount=" + executeCount + "--startTime=" + startTime);
        Date time = new Date();
        //删除上次拉取商品
        appGoodsService.deleteAppGoodsByAddUser("-116", time);
        Integer page = 1;
        int i = 0;
        while (true) {
            try {
                String a = "https://youngmall-api.youzibuy.com/index/itemList?device_id=863976047605057&bundleid=11&resolution=1080,2029&platform=android&mode=0&myclient=2330280001100000&tbuid=&sdkversion=28&v_auth=7.5LzGyazB03agj0kZ4oQoe3PTimaqJWzLvMpPRHaw90I&v=2.8.0&imei=863976047605057&myuid=321192232&app_id=23&page=" + page + "&sort_type=1";
                String sign = m1(a, "55ce50f066ef7602");
                String url = a + "&sign=" + sign;
                log.info("羊毛省钱请求链接{}" + url);
                String res = DtkHttpUtils.sendGet(url, null);
                JSONObject jsonObject = JSONObject.parseObject(res);
                JSONObject jsonObjectData = jsonObject.getJSONObject("data");
                Integer code = jsonObject.getInteger("code");
                if (code == 200) {
                    JSONArray result = jsonObjectData.getJSONArray("item_list");
                    if (result.size() == 0) {
                        break;
                    }
                    List<YoungmallItemInfo> bean = JsonUtils.getJsonToList(result.toJSONString(), YoungmallItemInfo.class);
                    AppCompany com = userCashschemeService.findCompanyAll();//查询公司加缓存
                    for (YoungmallItemInfo itemInfo : bean) {
                        if (StringUtils.isNotNull(itemInfo.getCoupon_amount_str())) {

                            AppGoods appGoods = new AppGoods();
                            if ("true".equals(itemInfo.getIs_new())) {
                                appGoods.setMsg("上新");
                            }
                            appGoods.setItemid(itemInfo.getNum_iid().toString());
                            appGoods.setRecommend(1);
                            appGoods.setAddUserId(-116);
                            if ("1".equals(itemInfo.getGoods_type()) || "0".equals(itemInfo.getGoods_type()) || itemInfo.getIs_free_item() != null) {
                                continue;
                            }
                            appGoods.setItemtitle(itemInfo.getTitle_display());
                            appGoods.setItempic(itemInfo.getPict_url());
                            appGoods.setSort(i++);
                            String coupon = RegUtils.getreGex(itemInfo.getCoupon_amount_str() == null ? "0元劵" : itemInfo.getCoupon_amount_str(), "(\\d+\\.\\d+)|(\\d+)");
                            String amount = RegUtils.getreGex(itemInfo.getRebate_amount_str() == null ? "返0" : itemInfo.getRebate_amount_str(), "(\\d+\\.\\d+)|(\\d+)");
                            appGoods.setItemprice(itemInfo.getReserve_price() == null ? "0" : itemInfo.getReserve_price().toString());

                            //返后价
                            BigDecimal zkPrice = new BigDecimal(itemInfo.getZk_final_price() == null ? 0d : itemInfo.getZk_final_price());
                            //补贴
                            BigDecimal amountPrice = new BigDecimal(amount == null ? "0" : amount);
                            //
                            appGoods.setItemendprice(zkPrice.add(amountPrice).doubleValue());
                            appGoods.setCouponmoney(new BigDecimal(coupon).doubleValue());
                            DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemInfo.getNum_iid().toString());
                            AppGoods goods = null;
                            if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {
                                goods = HDKUtils.getAppGoodsFromDTKYangMao(dtkResponse.getData(), appGoods);
                            } else {
                                HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(itemInfo.getNum_iid().toString());
                                if (info != null && info.getCode() == 1 && info.getData() != null) {
                                    goods = HDKUtils.getAppGoodsFromHDKYangMao(info.getData(), appGoods);
                                }
                            }
                            goods = appGoodsService.getMoneyInfoByGoodsId(com, goods);
                            Integer appGoodsNum = appGoodsMapper.selectCountByItemId(itemInfo.getNum_iid().toString());
                            if (appGoodsNum > 0) {
                                int update = appGoodsMapper.updateBatchByItemId(goods);
                            } else {
                                if (goods.getItemendprice() < 0) {
                                    continue;
                                }
                                int add = appGoodsMapper.insertAppGoods(goods);
                            }
//                            ServerResponse serverResponse = appGoodsService.addAppGoods(appGoods, -116);
//                            if (serverResponse.isSuccess()) {
//                                log.info("羊毛省钱首页推荐商品添加成功");
//                            }
                        } else {
                            log.info("羊毛省钱首页推荐商品添加失败  没有优惠卷{}" + itemInfo.getNum_iid());
                        }
                    }
                } else {
                    log.error("获取羊毛省钱首页推荐商品失败");
                    break;
                }
                page++;
                if (page == 10) {
                    redisTemplateService.batchDel("app_recommendGoods_lists" + 20 + "_" + 1,
                            "app_recommendGoods_lists" + 20 + "_" + 2,
                            "app_recommendGoods_lists" + 40 + "_" + 1,
                            "app_recommendGoods_lists" + 40 + "_" + 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取羊毛省钱首页推荐商品定时任务错误");
                break;
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行定时任务-获取羊毛省钱首页推荐商品-YoungmallTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    public static String m1(String str, String str2) {
        String c = g3(g2(g1(str)));
        return MD5Utils.getMD5(c + "&secretKey=" + str2);
    }

    public static String g3(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        boolean z = true;
        if (map.size() > 0) {
            for (Map.Entry next : map.entrySet()) {
                String str = (String) next.getKey();
                String str2 = (String) next.getValue();
                try {
                    str2 = URLDecoder.decode(str2, "utf-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (z) {
                    z = false;
                } else {
                    sb.append("&");
                }
                sb.append(str);
                sb.append("=");
                sb.append(str2);
            }
        }
        return sb.toString();
    }

    public static Map<String, String> g2(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        TreeMap treeMap = new TreeMap(new MapKeyComparator());
        treeMap.putAll(map);
        return treeMap;

    }

    public static Map<String, String> g1(String str) {
        if (str == null) {
            return null;
        }
        LinkedHashMap linkedHashMap = new LinkedHashMap();
        try {
            String substring = str.substring(str.indexOf(63) + 1);
            if (isNull(substring)) {
                return linkedHashMap;
            }
            for (String str2 : substring.split("&")) {
                int indexOf = str2.indexOf("=");
                linkedHashMap.put(URLDecoder.decode(str2.substring(0, indexOf), "UTF-8"), str2.substring(indexOf + 1).replaceAll("\n", "").trim());
            }
            return linkedHashMap;
        } catch (Exception e) {

        }
        return linkedHashMap;
    }

    public static boolean isNull(String str) {
        return str == null || str.length() == 0 || str.equals("null");
    }
}
